package com.w3c.pragmatic.controller;

import com.alibaba.fastjson.JSON;
import com.w3c.pragmatic.common.exception.BusinessException;
import com.w3c.pragmatic.domain.Response;
import com.w3c.pragmatic.domain.req.ProductPageReq;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.Random;

/**
 * 全局异常控制 前端控制器
 *
 * @author wangdong
 * @since 2025-02-20
 */
@Slf4j
@RestController
@RequestMapping("/exception")
@Api(tags = "全局异常控制控制层GlobalExceptionController")
public class GlobalExceptionController {

  /**
   * 业务执行后抛出异常议程
   *
   * @return String 成功描述
   */
  @ApiOperation(value = "业务执行后抛出异常议程", httpMethod = "GET")
  @RequestMapping(
      value = "/business",
      method = RequestMethod.GET,
      produces = MediaType.APPLICATION_JSON_VALUE)
  public Response<String> doBusinessException() {
    int random = new Random().nextInt(10);
    if (random < 3) return Response.ok("业务处理成功");
    else if (random < 7) throw new BusinessException("222222", "业务处理异常-case1");
    throw new BusinessException("业务处理异常-case2");
  }

  /**
   * 其他未知异常
   *
   * @return String 成功描述
   */
  @ApiOperation(value = "其他未知异常", httpMethod = "GET")
  @RequestMapping(
      value = "/unKnown",
      method = RequestMethod.GET,
      produces = MediaType.APPLICATION_JSON_VALUE)
  public Response<Object> doUnKnownException() {
    int random = new Random().nextInt(10);
    if (random < 5) return Response.ok("业务处理成功");
    // 这里抛出未捕获的异常
    int result = random / 0;
    return Response.ok(result);
  }

  /**
   * 三方定义异常
   *
   * @return String 成功描述
   */
  @ApiOperation(value = "三方定义异常", httpMethod = "POST")
  @RequestMapping(
      value = "/third",
      method = RequestMethod.POST,
      produces = MediaType.APPLICATION_JSON_VALUE)
  public Response<Object> doThirdException(@Valid @RequestBody ProductPageReq pageReq) {
    log.info("请求参数={}", JSON.toJSONString(pageReq));
    return Response.ok();
  }
}
